package com.example.demo.test.lecture.algorithm;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

public class  LengthOfLongestSubstring {
    public static void main(String[] args){
        String s = "abcabcbb";
        s = "abcbbaacfg";
//        s = "a";
        int i = 0;
        int flag = 0;
        int length = 0;
        while(i < s.length()){
            int pos = s.indexOf(s.charAt(i), flag);
            if(pos < i){
//                length = Math.max(i - 1 - pos, length);
                flag = pos + 1;
            }else{
                length = Math.max(i - flag + 1, length);
            }
            System.out.println("i: " + i + ", pos: " + pos + ", flag: " + flag + ", length: " + length + ", string: " + s.substring(flag, i+1));

            i++;
        }
        System.out.println("+++++++++++");
        System.out.println(length);

    }

    private static boolean repeatChars(String s, int start, int end){
        Set set = new HashSet();
        for(int i=start; i < end; i++){
            Character c = s.charAt(i);
            if(set.contains(c)) return false;
            set.add(c);
        }
        return true;
    }

    private static int  lengthOfLongestSubstring(String s){
        int n = s.length();
        Set<Character> set = new HashSet<>();
        int ans = 0, i = 0, j = 0;
        while(j < n && j < n){
            if(!set.contains(s.charAt(j))){
                set.add(s.charAt(j++));
                ans = Math.max(ans, j-i);
            }else{
                set.remove(s.charAt(i++));
            }
        }
        return ans;
    }

    private static int lengthOfLongestSubstringMap(String s){
        int n = s.length();
        int max = 0, left = 0, right = 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        for(; right < n; right++){
            if(map.containsKey(s.charAt(right))){
                left = Math.max(map.get(s.charAt(right)), left);
            }
            map.put(s.charAt(right), right + 1);
            max = Math.max(max, right - left + 1);
        }
        return max;
    }
}

